package cn.wzb.hrm.web.controller;

import cn.wzb.hrm.util.AjaxResult;
import cn.wzb.hrm.utils.FastDfsApiOpr;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
public class FastDfsController {

    //文件上传到fastdfs,返回文件的路径
    @RequestMapping(value = "/fastdfs/upload",method = RequestMethod.POST)
    public AjaxResult upload(MultipartFile file) {
        try {
            //扩展名
            String extName = FilenameUtils.getExtension(file.getOriginalFilename());
            //调用fastdfs工具上传到Fastdfs服务器
            String upload = FastDfsApiOpr.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(upload);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false);
        }
    }

    /*//文件删除功能
    @RequestMapping("/fastdfs/remove")
    public AjaxResult remove(@RequestBody FastdfsDto path) throws Exception {
        String realPath = path.getPath();
        String groupname = realPath.substring(1, 7);
        System.out.println("截取的组名---"+groupname);
        String filename = realPath.substring(8);
        System.out.println("截取的文件名+++"+filename);
        FastDfsApiOpr.delete(groupname,filename);
        System.out.println("执行删除文件后的方法-------------------");
        return AjaxResult.me();
    }*/
    //文件下载
   /* @RequestMapping("/fastdfs/download")
    public AjaxResult download(@RequestBody  FastdfsDto path, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String realPath = path.getPath();
        //http://192.168.88.131/group1/M00/00/01/wKhYg1592LaAaNm4AAIuCKSF7Xs013.jpg

        String[] strings = realPath.split("/");
        String filename = strings[4]+"/"+ strings[5]+"/"+ strings[6]+"/"+ strings[7];

        System.out.println("服务器组名3"+strings[3]);
        System.out.println("文件名"+filename);

        byte[] downLoadFile = FastDfsApiOpr.download(strings[3],filename);

        File file = new File("D:/Desktop/download/"+strings[7]);
        //建立输出字节流
        FileOutputStream fos = new FileOutputStream(file);
        //用FileOutputStream 的write方法写入字节数组
        fos.write(downLoadFile);
        System.out.println("写入成功");
        fos.flush();
        //为了节省IO流的开销，需要关闭
        fos.close();


        return AjaxResult.me();
    }*/

}
